<template>
  <view class="container">
    <view class="header">
      <text class="title">营销企划书列表</text>
    </view>

    <!-- 营销企划书列表 -->
    <view class="proposal-list">
      <view
        v-for="proposal in proposalList"
        :key="proposal.marketingProposalId"
        class="proposal-card"
      >
        <view class="card-header">
          <text class="proposal-name">{{
            proposal.marketingProposalName
          }}</text>
          <text
            class="proposal-status"
            :class="{
              'status-approved': proposal.auditStatus === '已审核',
              'status-pending': proposal.auditStatus !== '已审核',
            }"
          >
            {{ proposal.auditStatus }}
          </text>
        </view>
        <view class="card-body">
          <text class="proposal-info"
            >策划师: {{ proposal.plannerUserId }}</text
          >
          <text class="proposal-info"
            >部门经理: {{ proposal.departmentManagerUserId }}</text
          >
          <text class="proposal-info"
            >提交时间: {{ formatDate(proposal.submitTime) }}</text
          >
          <text class="proposal-info"
            >审核状态: {{ proposal.auditStatus }}</text
          >
          <text class="proposal-info"
            >审核结论: {{ proposal.auditResult || "未审核" }}</text
          >
          <text class="proposal-info"
            >审核意见: {{ proposal.auditFeedback || "无" }}</text
          >
        </view>

        <!-- 操作按钮 -->
        <view class="action-buttons">
          <button
            class="download-button"
            @click="downloadFile(proposal.marketingProposalFilePath)"
          >
            下载文件
          </button>
          <button class="audit-button" @click="openAuditDialog(proposal)">
            审核
          </button>
        </view>
      </view>
    </view>

    <!-- 审核对话框 -->
    <uni-popup ref="auditPopup" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="审核营销企划书"
        :value="auditResult"
        placeholder="请输入审核结论"
        @confirm="submitAudit"
      >
        <textarea
          v-model="auditFeedback"
          placeholder="请输入审核意见"
          class="audit-feedback-input"
        ></textarea>

        <!-- 通过和驳回按钮 -->
        <view class="audit-action-buttons">
          <button class="audit-approve-button" @click="handleAudit('通过')">
            通过
          </button>
          <button class="audit-reject-button" @click="handleAudit('驳回')">
            驳回
          </button>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { listProposal, updateProposal } from "@/api/bpm/proposal"; // 导入 API 方法

export default {
  data() {
    return {
      proposalList: [], // 营销企划书列表
      currentProposal: null, // 当前正在审核的企划书
      auditResult: "", // 审核结论
      auditFeedback: "", // 审核意见
    };
  },
  mounted() {
    this.loadProposals(); // 页面加载时获取数据
  },
  methods: {
    // 加载营销企划书列表
    async loadProposals() {
      try {
        const response = await listProposal();
        console.log("过来的列表: \n", response);
        this.proposalList = response.rows;
      } catch (error) {
        uni.showToast({
          title: "加载失败，请重试",
          icon: "none",
        });
      }
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString();
    },

    // 下载文件
    downloadFile(filePath) {
      if (filePath) {
        uni.downloadFile({
          url: filePath,
          success: (res) => {
            if (res.statusCode === 200) {
              const fs = wx.getFileSystemManager(); // 获取文件系统管理器
              fs.saveFile({
                tempFilePath: res.tempFilePath, // 临时文件路径
                success: (saveRes) => {
                  console.log("文件保存成功，路径:", saveRes.savedFilePath);

                  // 打开文件
                  uni.openDocument({
                    filePath: saveRes.savedFilePath,
                    fileType: "docx", // 根据文件类型设置
                    success: (openRes) => {
                      console.log("文件打开成功");
                    },
                    fail: (err) => {
                      console.error("文件打开失败:", err);
                    },
                  });
                },
                fail: (err) => {
                  console.error("文件保存失败:", err);
                },
              });
            }
          },
          fail: (err) => {
            console.error("文件下载失败:", err);
          },
        });
      } else {
        uni.showToast({
          title: "文件路径无效",
          icon: "none",
        });
      }
    },

    // 打开审核对话框
    openAuditDialog(proposal) {
      this.currentProposal = proposal;
      this.auditResult = proposal.auditResult || "";
      this.auditFeedback = proposal.auditFeedback || "";
      this.$refs.auditPopup.open();
    },

    // 处理审核操作（通过或驳回）
    handleAudit(action) {
      if (!this.auditFeedback) {
        uni.showToast({
          title: "请填写审核意见",
          icon: "none",
        });
        return;
      }

      // 设置审核结论、审核状态、实行情况和审核时间
      const data = {
        marketingProposalId: this.currentProposal.marketingProposalId,
        auditResult: action === "通过" ? "通过" : "未通过",
        auditFeedback: this.auditFeedback,
        auditStatus: "已审核",
        executeStatus: action === "通过" ? "未开始" : "未通过",
        auditTime: new Date().toISOString(), // 当前系统时间
      };

      // 提交审核
      this.submitAudit(data);
    },

    // 提交审核
    async submitAudit(data) {
      try {
        await updateProposal(data);
        uni.showToast({
          title: "审核成功",
          icon: "success",
        });
        this.loadProposals(); // 重新加载数据
        this.$refs.auditPopup.close(); // 关闭对话框
      } catch (error) {
        uni.showToast({
          title: "审核失败，请重试",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style scoped>
.audit-action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 12px;
}

.audit-approve-button,
.audit-reject-button {
  flex: 1;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.audit-approve-button {
  background-color: #28a745; /* 绿色 */
  color: white;
}

.audit-reject-button {
  background-color: #dc3545; /* 红色 */
  color: white;
}
.container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
}

.proposal-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.proposal-card {
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.proposal-name {
  font-size: 18px;
  font-weight: bold;
}

.proposal-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.status-approved {
  background-color: #d4edda;
  color: #155724;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.proposal-info {
  font-size: 14px;
  color: #666;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 12px;
}

.download-button,
.audit-button {
  flex: 1;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
}

.download-button {
  background-color: #007bff;
  color: white;
}

.audit-button {
  background-color: #28a745;
  color: white;
}

.audit-feedback-input {
  width: 100%;
  height: 100px;
  margin-top: 10px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}
</style>
